package com.inha.capstone;

import org.json.*;

import android.*;
import android.app.*;
import android.content.*;
import android.os.*;
import android.widget.*;

import com.facebook.android.*;
import com.inha.capstone.facebook.*;
import com.inha.capstone.facebook.SessionEvents.AuthListener;
import com.inha.capstone.facebook.SessionEvents.LogoutListener;

public class FacebookSetting extends Activity {
	public static final String APP_ID = "307654542594329";

    private LoginButton mLoginButton;
    private TextView mText;
    private ImageView mUserPic;
    private Handler mHandler;
	ProgressDialog dialog;

	final int AUTHORIZE_ACTIVITY_RESULT_CODE = 0;
	String[] permissions = {"offline_access", "publish_stream", "user_photos", "publish_checkins", "photo_upload"};
    
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.fbsetting);
	    // TODO Auto-generated method stub

        if (APP_ID == null) {
            Util.showAlert(this, "Warning", "Facebook Applicaton ID must be " +
                    "specified before running this example: see FbAPIs.java");
            return;
        }

       
        mHandler = new Handler();
        
        mText = (TextView)findViewById(R.id.newsetting_txt);
        mUserPic = (ImageView)findViewById(R.id.user_pic);
       	mLoginButton = (LoginButton) findViewById(R.id.login);
        
       	
        SessionEvents.addAuthListener(new FbAPIsAuthListener());
        SessionEvents.addLogoutListener(new FbAPIsLogoutListener());
        
        /*
		 * Source Tag: login_tag
		 */
        mLoginButton.init(this, AUTHORIZE_ACTIVITY_RESULT_CODE, Utility.mFacebook, permissions);
        
       	if(Utility.mFacebook.isSessionValid()) {
       		requestUserData();
       	}
        
     }
    
    @Override
    public void onResume() {
    	super.onResume();
    	if(Utility.mFacebook != null && !Utility.mFacebook.isSessionValid()) {
	    	mText.setText("로그아웃 상태입니다");
	        mUserPic.setImageBitmap(null);
    	}
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	switch(requestCode) {
    		/*
    		 * if this is the activity result from authorization flow, do a call back to authorizeCallback
    		 * Source Tag: login_tag
    		 */
	    	case AUTHORIZE_ACTIVITY_RESULT_CODE: {
	    		Utility.mFacebook.authorizeCallback(requestCode, resultCode, data);
	    		break;
	    	}
	    	
    	}
    }
	 

    /*
     * Callback for fetching current user's name, picture, uid.
     */
    public class UserRequestListener extends BaseRequestListener {

        public void onComplete(final String response, final Object state) {
        	JSONObject jsonObject;
			try {
				jsonObject = new JSONObject(response);
				
	        	final String picURL = jsonObject.getString("picture");
	        	final String name = jsonObject.getString("name");
	        	Utility.userUID = jsonObject.getString("id");
	        	
	        	mHandler.post(new Runnable() {
	                public void run() {
	                	mText.setText(name);
	    	        	mUserPic.setImageBitmap(Utility.getBitmap(picURL));
	                }
	            });
	        	
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }

    }
    /*
     * The Callback for notifying the application when authorization
     *  succeeds or fails.
     */
    
    public class FbAPIsAuthListener implements AuthListener {

        public void onAuthSucceed() {
        	requestUserData();
        }

        public void onAuthFail(String error) {
            mText.setText("인증에 실패했습니다" + error);
        }
    }
    
    /*
     * The Callback for notifying the application when log out
     *  starts and finishes.
     */
    public class FbAPIsLogoutListener implements LogoutListener {
        public void onLogoutBegin() {
            mText.setText("로그아웃 중...");
        }

        public void onLogoutFinish() {
            mText.setText("로그아웃 상태입니다");
            mUserPic.setImageBitmap(null);
        }
    }
    
    
    /*
     * Request user name, and picture to show on the main screen.
     */
    public void requestUserData() {
    	mText.setText("Facebook에서 정보를 얻어오는 중...");
    	Bundle params = new Bundle();
   		params.putString("fields", "name, picture");
		Utility.mAsyncRunner.request("me", params, new UserRequestListener());
    }
    
	}


